package cn.lianyutiantang.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.util.Base64;
import java.util.Enumeration;
import java.util.Properties;

/**
 * Created by lianyutiantang on 2018/7/26.
 */
public class FileUtil {

    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
    /**
     * 图片缩放
     *
     * @param originalFile 原图file
     * @param smallfile    缩略图file
     * @param suffixName   上传图片后缀名
     * @param request
     * @throws IOException
     */
    public static void zoomImage(File originalFile, File smallfile, String suffixName, HttpServletRequest request) throws IOException {
        int size = 128;//默认缩放大小
        if (StringUtils.isNotBlank(request.getParameter("size"))) {
            size = Integer.parseInt(request.getParameter("size"));
        }
        String same = String.valueOf(request.getParameter("same"));
        BufferedImage bufImg = ImageIO.read(originalFile);
        Image Itemp = bufImg.getScaledInstance(size, size, Image.SCALE_SMOOTH);
        double wr = 0, hr = 0;
        if (same.equals("false")) {
            wr = size * 1.0 / bufImg.getWidth();
            hr = size * 1.0 / bufImg.getHeight();
        } else {
            double rate = 1, rate1 = (double) size / ((double) bufImg.getWidth()), rate2 = (double) size / ((double) bufImg.getHeight());
            boolean bool = true;  //true按小的缩放比例进行缩放，输出的图片最大值都不超过w或h
            if (rate1 > 1 && rate2 > 1) {  //原图片小于要缩放的大小，则不进行缩放。
                rate = 1;
            } else {
                rate = bool ? (rate1 < rate2 ? rate1 : rate2) : (rate1 > rate2 ? rate1 : rate2);
            }
            wr = rate;
            hr = rate;
        }
        AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(wr, hr), null);
        Itemp = ato.filter(bufImg, null);
        ImageIO.write((BufferedImage) Itemp, suffixName, smallfile);//生成缩略图
    }


    /**
     * 图片缩放备份
     *
     * @param originalFile 原图file
     * @param smallfile    缩略图file
     * @param suffixName   上传图片后缀名
     * @throws IOException
     */
    public static void zoomImagebackup(File originalFile, File smallfile, String suffixName) throws IOException {
        int size = 128;//默认缩放大小

        String same = String.valueOf("true");
        BufferedImage bufImg = ImageIO.read(originalFile);
        Image Itemp = bufImg.getScaledInstance(size, size, Image.SCALE_SMOOTH);
        double wr = 0, hr = 0;
        if (same.equals("false")) {
            wr = size * 1.0 / bufImg.getWidth();
            hr = size * 1.0 / bufImg.getHeight();
        } else {
            double rate = 1, rate1 = (double) size / ((double) bufImg.getWidth()), rate2 = (double) size / ((double) bufImg.getHeight());
            boolean bool = true;  //true按小的缩放比例进行缩放，输出的图片最大值都不超过w或h
            if (rate1 > 1 && rate2 > 1) {  //原图片小于要缩放的大小，则不进行缩放。
                rate = 1;
            } else {
                rate = bool ? (rate1 < rate2 ? rate1 : rate2) : (rate1 > rate2 ? rate1 : rate2);
            }
            wr = rate;
            hr = rate;
        }
        AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(wr, hr), null);
        Itemp = ato.filter(bufImg, null);
        ImageIO.write((BufferedImage) Itemp, suffixName, smallfile);//生成缩略图
    }

    /**
     * 将图片文件转化为base64字符串
     *
     * @param imgFilePath
     * @return
     */
    public static String makePictureStr(String imgFilePath) {
        try {
            byte[] data = null;
            InputStream in = new FileInputStream(imgFilePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
            BASE64Encoder encoder = new BASE64Encoder();// 对字节数组Base64编码
            return encoder.encode(data);// 返回Base64编码过的字节数组字符串
        } catch (FileNotFoundException e) {
            logger.error("找不到文件" + imgFilePath);
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * base64字节生成图片
     *
     * @param base64
     * @param imgFilePath
     * @return
     */
    public static boolean makePicture(String base64,String imgFilePath,String fileName ) {
        if (base64 == null) {
            return false;
        }
        File file =new File(imgFilePath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(base64);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }

            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath+"/"+fileName);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }




    public static boolean isOSLinux() {
        Properties prop = System.getProperties();
        String os = prop.getProperty("os.name");
        logger.info("当前运行系统为："+os);
        return os != null && os.toLowerCase().indexOf("linux") > -1;
    }
    /**
     * 获取服务器地址
     *
     * @return Ip地址
     */
    public static String getServerIp() {
        // 获取操作系统类型
        String sysType = System.getProperties().getProperty("os.name");
        String ip;
        if (sysType.toLowerCase().startsWith("win")) {  // 如果是Windows系统，获取本地IP地址
            String localIP = null;
            try {
                localIP = InetAddress.getLocalHost().getHostAddress();
                //localIP = String.valueOf(InetAddress.getLocalHost().getAddress());
            } catch (UnknownHostException e) {
                logger.error(e.getMessage(), e);
            }
            if (localIP != null) {
                return localIP;
            }
        } else {
            ip = getIpByEthNum("eth0"); // 兼容Linux
            if (ip != null) {
                return ip;
            }
        }
        return "获取服务器IP错误";
    }
    /**
     * 根据网络接口获取IP地址
     * @param ethNum 网络接口名，Linux下是eth0
     * @return
     */
    private static String getIpByEthNum(String ethNum) {
        try {
            Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                if (ethNum.equals(netInterface.getName())) {
                    Enumeration addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        ip = (InetAddress) addresses.nextElement();
                        if (ip != null && ip instanceof Inet4Address) {
                            return ip.getHostAddress();
                        }
                    }
                }
            }
        } catch (SocketException e) {
            logger.error(e.getMessage(), e);
        }
        return "获取服务器IP错误";
    }
    public static void main(String args[]){
//        FileUtil.isOSLinux();
       // System.out.println(getServerIp());
        try {
            System.out.println(encodeBase64File("C:\\Users\\OPJJ-JSJ-0010\\Desktop\\testfile\\timg (15).jpg"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 判断文件是否存在
     * @param httpPath
     * @return
     */
    public static Boolean existHttpPath(String httpPath){
        URL httpurl = null;
        try {
            httpurl = new URL(new URI(httpPath).toASCIIString());
            URLConnection urlConnection = httpurl.openConnection();
            // urlConnection.getInputStream();
            Long TotalSize=Long.parseLong(urlConnection.getHeaderField("Content-Length"));
            return TotalSize > 0;
        } catch (Exception e) {
            logger.debug(httpurl + "文件不存在");
            return false;
        }
    }

    /**
     * 将文件转成base64 字符串
     * @return *
     * @throws Exception
     */
    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return new BASE64Encoder().encode(buffer);
    }
    /**
     * 将base64字符解码保存文件
     *
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
    public static void decoderBase64File(String base64Code, String targetPath,String catalogue)
            throws Exception {
        File file = new File(catalogue);
        if(file.exists()==false){
            file.mkdirs();
        }
        byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }

    public static Boolean base64ToFile(String base64,String filePath, String fileName) {
        File file = null;
        //创建文件目录
       // String filePath="D:\\image";
        File  dir=new File(filePath);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }
        BufferedOutputStream bos = null;
        java.io.FileOutputStream fos = null;
        try {
            byte[] bytes = Base64.getDecoder().decode(base64);
            file=new File(filePath+"/"+fileName);
            fos = new java.io.FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            }
        }
        return true;
    }

}
